import { Graph } from '@antv/x6';
import React, { useLayoutEffect, useRef } from 'react';
import client from "../../utils/client";
import styles from './editor.module.css';

export default function Viewer({ id }) {
  const content_container = useRef();
  const graph_ref = useRef();

  // 注册节点类型
  function registerNode() {
    const ports = {
      groups: {
        top: {
          position: 'top',
          attrs: {
            circle: {
              r: 4,
              magnet: true,
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: '#fff',
              style: {
                visibility: 'hidden',
              },
            },
          },
        },
        right: {
          position: 'right',
          attrs: {
            circle: {
              r: 4,
              magnet: true,
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: '#fff',
              style: {
                visibility: 'hidden',
              },
            },
          },
        },
        bottom: {
          position: 'bottom',
          attrs: {
            circle: {
              r: 4,
              magnet: true,
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: '#fff',
              style: {
                visibility: 'hidden',
              },
            },
          },
        },
        left: {
          position: 'left',
          attrs: {
            circle: {
              r: 4,
              magnet: true,
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: '#fff',
              style: {
                visibility: 'hidden',
              },
            },
          },
        },
      },
      items: [
        {
          group: 'top',
        },
        {
          group: 'right',
        },
        {
          group: 'bottom',
        },
        {
          group: 'left',
        },
      ],
    }

    // 开始
    Graph.registerNode(
      'node-1',
      {
        inherit: 'circle',
        label: '开始',
        width: 40,
        height: 40,
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: 'green',
            fill: '#EFF4FF',
          },
          text: {
            fontSize: 12,
            fill: '#262626',
          },
        },
        ports: { ...ports },
        data: {
          类型: 1,
          名称: '开始',
          状态描述: '待提交',
        },
      },
      true,
    );

    // 结束
    Graph.registerNode(
      'node-2',
      {
        inherit: 'circle',
        label: '结束',
        width: 40,
        height: 40,
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: '#CCCCCC',
            fill: '#EFF4FF',
          },
          text: {
            fontSize: 12,
            fill: '#262626',
          },
        },
        ports: { ...ports },
        data: {
          类型: 2,
          名称: '结束',
          状态描述: '已结束',
        },
      },
      true,
    );

    // 审批
    Graph.registerNode(
      'node-3',
      {
        inherit: 'rect',
        label: '审批',
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: '#5F95FF',
            fill: '#EFF4FF',
          },
          text: {
            fontSize: 12,
            fill: '#262626',
          },
        },
        ports: { ...ports },
        data: {
          类型: 3,
          名称: '审批',
          状态描述: '待审批',
        },
      },
      true,
    );

    // 会签
    Graph.registerNode(
      'node-4',
      {
        inherit: 'rect',
        label: '会签',
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: '#5F95FF',
            fill: '#EFF4FF',
            rx: 10,
            ry: 10,
          },
          text: {
            fontSize: 12,
            fill: '#262626',
          },
        },
        ports: { ...ports },
        data: {
          类型: 4,
          名称: '会签',
          状态描述: '待会签',
        },
      },
      true,
    );

    // 虚拟
    Graph.registerNode(
      'node-5',
      {
        inherit: 'circle',
        label: '虚拟',
        width: 40,
        height: 40,
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: '#5F95FF',
            fill: '#EFF4FF',
          },
          text: {
            fontSize: 12,
            fill: '#262626',
          },
        },
        ports: { ...ports },
        data: {
          类型: 5,
          名称: '虚拟',
          状态描述: '虚拟',
        },
      },
      true,
    );
  }

  // 初始化画布
  function initGraph() {
    registerNode();

    return new Graph({
      container: content_container.current,
      autoResize: true,
      interacting: {
        nodeMovable: false,
        edgeMovable: false,
      },
      panning: {
        enabled: true,
      },
      mousewheel: {
        enabled: true,
        modifiers: 'ctrl',
        minScale: 0.5,
        maxScale: 3,
      },
      connecting: {
        router: 'manhattan',
        connector: {
          name: 'rounded',
          args: {
            radius: 8,
          },
        },
        anchor: 'center',
        connectionPoint: 'anchor',
        allowLoop: false,
        allowBlank: false,
        allowMulti: false,
        allowNode: false,
        snap: {
          radius: 20,
        },
      },
    });
  }

  useLayoutEffect(() => {
    if (graph_ref.current) return; // 避免重复初始化
    graph_ref.current = initGraph();
    load(id);
    window['__workflow_viewer_' + id] = () => {
      client.job('B.Flow_UpdateUser', {
        InstanceID: id,
      }).then(() => {
        load(id);
      });
    };
    return () => {
      delete window['__workflow_viewer_' + id];
    }
    // eslint-disable-next-line
  }, []);

  function load(id) {
    if (!id) return;
    // 加载实例信息
    client.job('B.Flow_GetState', {
      InstanceID: id,
    }).then(({ current, waiting, history }) => {
      history.filter(h => !h.回滚标记).forEach(h => {
        if (history[h.通过节点]) {
          history[h.通过节点].push(h);
        } else {
          history[h.通过节点] = [h];
        }
      });

      // 加载流程图
      Promise.all([
        client.job('CardR', {
          Card: 'B.流程节点',
          Model: null,
          Filter: [['流程定义', '=', current.流程定义]],
        }),
        client.job('CardR', {
          Card: 'B.流程路径',
          Model: null,
          Filter: [['流程定义', '=', current.流程定义]],
        })]).then(([{ Rows: nodes }, { Rows: edges }]) => {
          const cells = [];

          nodes.forEach(node => {
            const tools = [];
            // 当前节点显示待办人员信息
            if (!current.结束标记 && current.当前节点 === node.ID) {
              tools.push({
                "name": 'button',
                "args": {
                  "x": node.宽度 / 2,
                  "y": 0.9,
                  "markup": [
                    {
                      "tagName": 'text',
                      "textContent": waiting.map(w => w['待办用户.名称'] ?? w.待办用户).join(','),
                      "selector": 'text',
                      "attrs": {
                        "fill": "red",
                        "font-size": 10,
                        "text-anchor": 'middle',
                        "cursor": "pointer",
                        "onclick": "Base.alert('文本内容', this.textContent)"
                      },
                    },
                    {
                      "tagName": 'title',
                      "selector": 'title',
                      "textContent": waiting.map(w => w['待办用户.用户名'] ?? w.待办用户).join(','),
                    },
                  ],
                },
              });
              tools.push({
                "name": 'button',
                "args": {
                  "x": node.宽度 - 16,
                  "y": 0,
                  "markup": [
                    {
                      "tagName": 'path',
                      "attrs": {
                        "id": id,
                        "fill": "red",
                        "transform": "scale(0.016)",
                        "d": "M512 63.5C264.3 63.5 63.5 264.3 63.5 512S264.3 960.5 512 960.5 960.5 759.7 960.5 512 759.7 63.5 512 63.5zM198 509.6h87.6c0-136.3 102.3-243.4 233.7-238.5 43.8 0 82.8 14.6 121.7 34.1L597.2 349c-24.4-9.8-53.6-19.5-82.8-19.5-92.5 0-170.4 77.9-170.4 180.1h87.6L314.8 631.3 198 509.6z m540.3-0.1c0 131.4-102.2 243.4-228.8 243.4-43.8 0-82.8-19.4-121.7-38.9l43.8-43.8c24.4 9.8 53.6 19.5 82.8 19.5 92.5 0 170.4-77.9 170.4-180.1h-92.5l116.9-121.7L826 509.5h-87.7z",
                        "cursor": "pointer",
                        "onclick": '__workflow_viewer_' + id + '()',
                      }
                    },
                    {
                      "tagName": 'title',
                      "selector": 'title',
                      "textContent": "刷新待办用户",
                    },
                  ],
                },
              });
            }

            // 历史节点显示审批人
            if (history[node.ID]) {
              tools.push({
                "name": 'button',
                "args": {
                  "x": node.宽度 / 2,
                  "y": 0.9,
                  "markup": [
                    {
                      "tagName": 'text',
                      "textContent": history[node.ID].map(h => h['创建用户.名称'] ?? h.创建用户).join(','),
                      "selector": 'text',
                      "attrs": {
                        "fill": "darkgreen",
                        "font-size": 10,
                        "text-anchor": 'middle',
                        "onclick": "Base.alert('文本', this.textContent)"
                      },
                    },
                    {
                      "tagName": 'title',
                      "selector": 'title',
                      "textContent": history[node.ID].map(h => (h.意见 ?? '~') + ' @' + h.创建时间.format('YYYY-MM-DD HH:mm:ss')).join('\n'),
                    },
                  ],
                },
              });
            }

            cells.push({
              "id": node.ID,
              "shape": "node-" + node.类型,
              "label": node.名称,
              "position": {
                "x": node.坐标X,
                "y": node.坐标Y,
              },
              "size": {
                "width": node.宽度,
                "height": node.高度,
              },
              "attrs": {
                "body": {
                  "stroke": !current.结束标记 && current.当前节点 === node.ID ? 'red' : undefined,
                  "fill": history[node.ID] ? '#DADAE1' : undefined,
                },
              },
              "tools": tools,
              "data": node,
              "ports": {
                "groups": {
                  "top": {
                    "position": "top",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#5F95FF",
                        "strokeWidth": 1,
                        "fill": "#fff",
                        "style": {
                          "visibility": "hidden"
                        }
                      }
                    }
                  },
                  "right": {
                    "position": "right",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#5F95FF",
                        "strokeWidth": 1,
                        "fill": "#fff",
                        "style": {
                          "visibility": "hidden"
                        }
                      }
                    }
                  },
                  "bottom": {
                    "position": "bottom",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#5F95FF",
                        "strokeWidth": 1,
                        "fill": "#fff",
                        "style": {
                          "visibility": "hidden"
                        }
                      }
                    }
                  },
                  "left": {
                    "position": "left",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#5F95FF",
                        "strokeWidth": 1,
                        "fill": "#fff",
                        "style": {
                          "visibility": "hidden"
                        }
                      }
                    }
                  }
                },
                "items": [
                  {
                    "group": "top",
                    "id": node.ID + '-0'
                  },
                  {
                    "group": "right",
                    "id": node.ID + '-1'
                  },
                  {
                    "group": "bottom",
                    "id": node.ID + '-2'
                  },
                  {
                    "group": "left",
                    "id": node.ID + '-3'
                  }
                ]
              },
            });
          });

          edges.forEach(edge => {
            const passed = history[edge.入口节点]?.some(h => h.到达节点 === edge.出口节点);
            cells.push({
              "id": edge.ID,
              "shape": "edge",
              "attrs": {
                "line": {
                  "stroke": "#A2B1C3",
                  "strokeWidth": passed ? 4 : 2,
                  "targetMarker": {
                    "name": "block",
                    "width": 12,
                    "height": 8
                  }
                }
              },
              "defaultLabel": {
                "markup": [
                  {
                    "tagName": "rect",
                    "selector": "body"
                  },
                  {
                    "tagName": "text",
                    "selector": "label"
                  }
                ],
                "attrs": {
                  "text": {
                    "fill": "#262626",
                    "fontSize": 12,
                    "textAnchor": "middle",
                    "textVerticalAnchor": "middle",
                    "pointerEvents": "none"
                  },
                  "rect": {
                    "ref": "label",
                    "fill": "transparent",
                    "rx": 3,
                    "ry": 3,
                    "refWidth": 1,
                    "refHeight": 1,
                    "refX": 0,
                    "refY": 0
                  }
                },
                "position": {
                  "distance": edge.标签偏移 ?? 0.5,
                  "offset": -10,
                  "options": {
                    "keepGradient": true
                  }
                }
              },
              "label": edge.名称,
              "data": edge,
              "source": {
                "cell": edge.入口节点,
                "port": edge.入口节点 + "-" + edge.入口锚点
              },
              "target": {
                "cell": edge.出口节点,
                "port": edge.出口节点 + "-" + edge.出口锚点
              }
            });
          })

          graph_ref.current.fromJSON({ cells });
          graph_ref.current.centerContent();
        });
    });
  }

  return (
    <div className={styles.editor}>
      <div className={styles.content} ref={content_container}></div>
    </div>
  );
}